package com.xqls.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xqls.bean.BlockBean;
import com.xqls.dal.dao.BlockDao;
import com.xqls.dal.model.Block;
import com.xqls.dal.model.BlockExample;
import com.xqls.service.BlockService;
import com.xqls.util.ObjectUtil;

@Service
public class BlockServiceImpl implements BlockService{

	@Autowired private BlockDao blockDao;
	
	@Override
	public boolean add(BlockBean bean){
		boolean success = false;
		Block record = (Block) ObjectUtil.transfer(bean, Block.class);
		int result = blockDao.insert(record);
		if(result>0){
			Block parent = blockDao.queryByKey(record.getPraentId());
			Block block = new Block();
			block.setBlockId(record.getBlockId());
			if(parent == null){
				block.setBlockUrl(record.getBlockId()+";");
			}else{
				block.setBlockUrl(parent.getBlockUrl()+record.getBlockId()+";");
			}
			success = blockDao.update(block);
		}
		return success;
	}
	
	@Override
	public boolean delete(Integer key){
		boolean success = false;
		success = blockDao.delete(key);
		blockDao.deleteByPraentKey(key);
		return success;
	}
	
	@Override
	public boolean update(BlockBean bean){
		Block praent = null;
		if(bean.getPraentId() != null){
			praent = blockDao.queryByKey(bean.getPraentId());
		}else{
			Block block = blockDao.queryByKey(bean.getBlockId());
			praent = blockDao.queryByKey(block.getPraentId());
		}
		Block record = (Block) ObjectUtil.transfer(bean, Block.class);
		record.setBlockUrl(praent.getBlockUrl()+record.getBlockId()+";");
		return blockDao.update(record);
	}
	
	@Override
	public BlockBean queryByKey(Integer key){
		return (BlockBean) ObjectUtil.transfer(blockDao.queryByKey(key), BlockBean.class);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<BlockBean> queryByParentKey(Integer praentKey){
		BlockExample example = new BlockExample();
		example.createCriteria().andPraentIdEqualTo(praentKey);
		return ObjectUtil.transferList(blockDao.queryByExample(example), BlockBean.class);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<BlockBean> queryList(BlockExample example){
		return ObjectUtil.transferList(blockDao.queryByExample(example), BlockBean.class);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<BlockBean> queryList(Map<String, Object> map){
		return ObjectUtil.transferList(blockDao.queryList(map), BlockBean.class);
	}
}
